//
//  RequestManager.m
//  Product_A
//
//  Created by lanou on 16/5/10.
//  Copyright © 2016年 lanou. All rights reserved.
//

#import "RequestManager.h"

@implementation RequestManager
#pragma mark----处理字典与NSData之间转换
+(NSData *)dicToDataWithDic:(NSDictionary *)dic
{
    NSMutableArray *array = [NSMutableArray array];
    for (NSString *key in dic)
    {
        NSString *string = [NSString stringWithFormat:@"%@=%@",key,dic[key]];
        [array addObject:string];
    }
    NSString *dataString = [array componentsJoinedByString:@"&"];
    
    return [dataString dataUsingEncoding:NSUTF8StringEncoding];
}
+(void)initWithUrlString:(NSString *)urlString
                      requestType:(NSString *)requestType
                           parDic:(NSDictionary *)parDic
                      finishBlock:(RequestFinish)finishBlock
                       errorBlock:(RequestError)errorBlock
{
   
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]];
        if ([requestType isEqualToString:@"POST"])
        {
            [request setHTTPMethod:@"POST"];
            if (parDic.count !=0)
            {
                [request setHTTPBody:[self dicToDataWithDic:parDic]];
            }
        }
        
        NSURLSession *session = [NSURLSession sharedSession];
        NSURLSessionDataTask *task = [session dataTaskWithRequest: request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error)
        {
            if (error)
            {
                if (errorBlock)
                {
                     errorBlock(error);
                }
            }else
            {
                if (finishBlock)
                {
                    finishBlock(data);
                }
            }
        }];
        [task resume];
}
@end
